<?php
declare (strict_types = 1);

namespace app\middleware;

use app\common\lib\ApiToken;
use think\facade\Request;

class CheckAuth
{
    // http header authorization
    public static $authKey = 'authorization';
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $info = Request::header();
        if (array_key_exists(self::$authKey, $info) && !empty($info[self::$authKey])){
            /*
             * 获取头部的  authorization
             */
            $auth_id = $info[self::$authKey];
        } else {
            if(array_key_exists(self::$authKey, $_COOKIE) && $_COOKIE[self::$authKey]){
                /*
                 * 获取cookie中的authorization
                 */
                $auth_id = $_COOKIE[self::$authKey];
            }
        }
        if (!empty($auth_id)){
            // 设置authorization的值
            ApiToken::setId($auth_id);
        } else {
            /*
             * authorization的值不存在则创建一个
             */
            ApiToken::setId();
        }
        //
        return $next($request);
    }
}
